/*
 * Position.java
 *
 * Created on Jun 12, 2007, 7:15:43 PM
 *
 * Copyright (c) 2007 Daniel Gronau
 *
 * This file is part of KanjiTori.
 *
 * KanjiTori is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * KanjiTori is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */

package kanjitori.map;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author DGronau
 */

;

public class Position {
    
    public enum Direction { LOWER_LEFT, LEFT, UPPER_LEFT, LOWER, UPPER, LOWER_RIGHT, RIGHT, UPPER_RIGHT};
    
    private final static Position[] NEIGHBORS = new Position[] 
    {  Position.get(-1, -1), Position.get(-1, 0), Position.get(-1, 1), Position.get(0, -1), 
       Position.get(0, 1), Position.get(1, -1), Position.get(1, 0), Position.get(1, 1) };


    private static Map<String, Position> map = new HashMap<String, Position>();

    private int x;
    private int y;

    private Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int x() {
        return x;
    }

    public int y() {
        return y;
    }

    public Position add(Position p) {
        return get(x + p.x, y + p.y);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Position) {
            return equals((Position) o);
        } else {
            return false;
        }
    }

    public boolean equals(Position pos) {
        return x == pos.x && y == pos.y;
    }

    @Override
    public int hashCode() {
        return 3 * x + 65537 * y;
    }

    public static Position get(int x, int y) {
        String key = getKey(x, y);
        Position pos = map.get(key);
        if (pos == null) {
            pos = new Position(x, y);
            map.put(key, pos);
        }
        return pos;
    }
    
    public Position getNeighbor(Direction direction) {
        return get(x + NEIGHBORS[direction.ordinal()].x, 
                   y + NEIGHBORS[direction.ordinal()].y);
    }

    private static String getKey(int x, int y) {
        return "" + x + ":" + y;
    }
}
